<template>
  <q-page class="q-pa-md">
    <q-btn class="float-right" color="primary" icon="arrow_back" outline title="返回" to="/" />
    <div class="q-pb-md text-h5">集货</div>
    <!--错误提示-->
    <q-banner class="text-white bg-red q-mb-md" dense inline-actions v-if="serverErrorMessage">
      {{ serverErrorMessage }}
      <template v-slot:action>
        <q-btn @click="serverErrorMessage = ''" dense flat icon="close" size="sm" />
      </template>
    </q-banner>
    <!--成功提示-->
    <q-banner class="text-white bg-green q-mb-md" dense inline-actions v-if="serverSuccessMessage">
      {{ serverSuccessMessage }}
      <template v-slot:action>
        <q-btn @click="serverSuccessMessage = ''" dense flat icon="close" size="sm" />
      </template>
    </q-banner>
    <div class="row q-col-gutter-sm col-12">
      <div class="col-12">
        <q-icon color="red" name="fas fa-asterisk" size="10px" />
        <span>拣货明细ID</span>
        <easy-input v-model="$d.pickLineId" :disable="pickLineIdLoadingState" @keyup.enter="validPickLineId"
          :loading="pickLineIdLoadingState" @focus="fx.ui.select" ref="pickLineId" :error="v$.pickLineId.$error"
          :error-message="e$(v$.pickLineId.$errors)"/>
      </div>
      <div class="col-12">
        <q-icon color="red" name="fas fa-asterisk" size="10px" v-if="$d.pickLineInfo.packPickLinesCount > 1
        && !$d.pickLineInfo.collectContainer" />
        <span>容器号</span>
        <easy-input v-model="$d.collectContainer" @focus="fx.ui.select" ref="pickLineId"
          :readonly="!!(($d.pickLineInfo.packPickLinesCount === 1) || ($d.pickLineInfo.packPickLinesCount > 1
          && $d.pickLineInfo.collectContainer))" :error="v$.collectContainer.$error"
          :error-message="e$(v$.collectContainer.$errors)"/>
      </div>
      <div class="col-6 q-pl-none">
        <q-checkbox dence v-model="$d.isPrintCollectLabel" label="打印集货标签" />
      </div>
      <div class="row col-6 justify-center" v-if="$d.pickLineInfo.packPickLinesCount">
        <div style="line-height: 40px">
          {{$d.pickLineInfo.collectedPackPickLinesCount}}/{{$d.pickLineInfo.packPickLinesCount}}
        </div>
      </div>
      <div class="col-12">
        <q-btn class="full-width" color="primary" label="确定集货"
          @click="doCollectByPda" :loading="submittingState" :disable="!$d.pickLineInfo.isAbleToCollect" />
      </div>
    </div>
  </q-page>
</template>

<script lang="ts">
export default {
  name: 'CollectStd'
}
</script>

<script lang="ts" setup>

import {computed, nextTick, reactive, ref} from 'vue'
import useVuelidate from '@vuelidate/core'
import {CollectByPdaReq, PickLineInfoForCollect} from '../../defs/collect'
import {playErrorSound, playSuccessSound} from '@njt/wms/helper/audio'
import {QInput, useQuasar} from 'quasar'
import {WmPack} from '@njt/wms/defs/work/pack'
import _ from 'lodash'

let serverErrorMessage = ref('')
let serverSuccessMessage = ref('')
let submittingState = ref(false)
let pickLineIdLoadingState = ref(false)
//是否可以集货
let isValidPickLine = ref(false)
const $d = reactive({
  pickLineId: '',
  orderId: '',
  pickLineInfo: {} as PickLineInfoForCollect,
  collectContainer: '' as string | null,
  isPrintCollectLabel: true,
  caseId: '' as string | null
})

const $q = useQuasar()

const validators = $f.validators
const rules = {
  pickLineId: {
    required: validators.required,
    int32: validators.int32
  },
  collectContainer: {
    required: validators.requiredIf(computed(() => {
      return $d.pickLineInfo.packPickLinesCount > 1 && !$d.pickLineInfo.collectContainer
    }))
  }
}
const v$ = useVuelidate(rules,computed(() => $d),{$autoDirty: true})
//确定集货
const doCollectByPda = function () {
  serverErrorMessage.value = ''
  void v$.value
    .$validate()
    .then((valRes) => {
      if (valRes) {
        submittingState.value = true
        let params = {
          pickLineId: $d.pickLineId,
          collectContainer: $d.collectContainer,
          isNeedPrintLabel: $d.isPrintCollectLabel
        }
        $f.axios
          .post<CollectByPdaReq>('/wms/work/order/collect-by-pda',params)
          .then((resp) => {
            window.localStorage.setItem('isPrintCollectLabel', String($d.isPrintCollectLabel))
            let parameters = resp.data.packInfoForNlpPrint
            $d.caseId = resp.data.caseId
            let isPackCollectedDone = resp.data.isPackCollectedDone
            if ($d.isPrintCollectLabel && isPackCollectedDone) {
              return nlpPrint(parameters)
            } else {
              return new Promise<void>((resolve) => { resolve() })
            }
          })
          .then(() => {
            serverSuccessMessage.value = '操作成功,箱号:' + $d.caseId
            playSuccessSound()
          })
          .catch((err) =>{
            playErrorSound()
            serverErrorMessage.value = $f.getAxiosErrMsg(err)
          })
          .finally(() => {
            submittingState.value = false
            $d.pickLineId = ''
            $d.collectContainer = null
            resetPickLineInfo()
            void nextTick(() => {
              pickLineId.value && pickLineId.value.focus()
              v$.value.$reset()
            })
          })
      } else {
        playErrorSound()
      }
    })
}

const nlpPrint = (form: WmPack) => {
  let nlpUrl = localStorage.getItem('nlpUrl') || ''
  if (nlpUrl && form.packsForLblPrint.length > 0) {
    let printTasks = []
    $q.loading.show({
      spinnerSize: 40,
      message: '标签打印中...'
    })
    if (form.packLblType === 0) {
      // 单料
      let packInfo = form.packsForLblPrint[0]
      packInfo.currentPage = 1
      packInfo.allPages = 1
      let paramsForPrint = {
        LabelName: form.caseDefLblName,
        PrinterName: form.caseDefPrinterNo,
        Parameters: packInfo,
        PrintNum: 1
      }
      printTasks.push($f.axios.post(nlpUrl, paramsForPrint))
    } else if (form.packLblType === 1) {
      // 多料
      let currentPage = 1
      let allPages = 0
      let caseDefSubLblSkuCapacity = form.caseDefSubLblSkuCapacity
      allPages = _.chunk(form.packsForLblPrint, caseDefSubLblSkuCapacity).length + 1
      // 主标签
      let packInfo = {} as Record<string, any>
      packInfo['caseId'] = form.packsForLblPrint[0].caseId
      packInfo['consigneePackNo'] = form.packsForLblPrint[0].consigneePackNo
      packInfo['weightPn'] = form.packsForLblPrint[0].weightPn
      packInfo['packLength'] = form.packsForLblPrint[0].packLength
      packInfo['packWidth'] = form.packsForLblPrint[0].packWidth
      packInfo['packHeight'] = form.packsForLblPrint[0].packHeight
      packInfo['orderNo'] = form.packsForLblPrint[0].orderNo
      packInfo['orderDt'] = form.packsForLblPrint[0].orderDt
      packInfo['consigneeName'] = form.packsForLblPrint[0].consigneeName
      packInfo['consigneeFullName'] = form.packsForLblPrint[0].consigneeFullName
      packInfo['storerRefNo'] = form.packsForLblPrint[0].storerRefNo
      packInfo['consigneeRefNo'] = form.packsForLblPrint[0].consigneeRefNo
      packInfo['otherRefNo'] = form.packsForLblPrint[0].otherRefNo
      packInfo['invoiceNo'] = form.packsForLblPrint[0].invoiceNo
      packInfo['packCnt'] = form.packsForLblPrint[0].packCnt
      for (let i = 0; i < form.packsForLblPrint.length; i++) {
        packInfo['skuId' + (i + 1)] = form.packsForLblPrint[i].skuId
        packInfo['sku' + (i + 1)] = form.packsForLblPrint[i].sku
        packInfo['skuName' + (i + 1)] = form.packsForLblPrint[i].skuName
        packInfo['skuNameE' + (i + 1)] = form.packsForLblPrint[i].skuNameE
        packInfo['spec' + (i + 1)] = form.packsForLblPrint[i].spec
        packInfo['qty' + (i + 1)] = form.packsForLblPrint[i].qty
        packInfo['customerSku' + (i + 1)] = form.packsForLblPrint[i].customerSku
        packInfo['customerSpec' + (i + 1)] = form.packsForLblPrint[i].customerSpec
        packInfo['customerPo' + (i + 1)] = form.packsForLblPrint[i].customerPo
        packInfo['storerSo' + (i + 1)] = form.packsForLblPrint[i].storerSo
        packInfo['gw' + (i + 1)] = form.packsForLblPrint[i].gw
        packInfo['nw' + (i + 1)] = form.packsForLblPrint[i].nw
        packInfo['cube' + (i + 1)] = form.packsForLblPrint[i].cube
      }
      packInfo.currentPage = currentPage
      packInfo.allPages = allPages
      let paramsForPrint = {
        LabelName: form.caseDefMultiSkuMasterLblName,
        PrinterName: form.caseDefPrinterNo,
        Parameters: packInfo,
        PrintNum: 1
      }
      printTasks.push($f.axios.post(nlpUrl, paramsForPrint))
      // 副标签
      _.chunk(form.packsForLblPrint, caseDefSubLblSkuCapacity).forEach((item, index, arr) => {
        packInfo = {}
        packInfo['caseId'] = item[0].caseId
        packInfo['consigneePackNo'] = item[0].consigneePackNo
        packInfo['weightPn'] = item[0].weightPn
        packInfo['packLength'] = item[0].packLength
        packInfo['packWidth'] = item[0].packWidth
        packInfo['packHeight'] = item[0].packHeight
        packInfo['orderNo'] = item[0].orderNo
        packInfo['orderDt'] = item[0].orderDt
        packInfo['consigneeName'] = item[0].consigneeName
        packInfo['consigneeFullName'] = item[0].consigneeFullName
        packInfo['storerRefNo'] = item[0].storerRefNo
        packInfo['consigneeRefNo'] = item[0].consigneeRefNo
        packInfo['otherRefNo'] = item[0].otherRefNo
        packInfo['invoiceNo'] = item[0].invoiceNo
        packInfo['packCnt'] = item[0].packCnt
        for (let i = 0; i < item.length ; i++) {
          packInfo['skuId' + (i + 1)] = item[i].skuId
          packInfo['sku' + (i + 1)] = item[i].sku
          packInfo['skuName' + (i + 1)] = item[i].skuName
          packInfo['skuNameE' + (i + 1)] = item[i].skuNameE
          packInfo['spec' + (i + 1)] = item[i].spec
          packInfo['qty' + (i + 1)] = item[i].qty
          packInfo['customerSku' + (i + 1)] = item[i].customerSku
          packInfo['customerSpec' + (i + 1)] = item[i].customerSpec
          packInfo['customerPo' + (i + 1)] = item[i].customerPo
          packInfo['storerSo' + (i + 1)] = item[i].storerSo
          packInfo['gw' + (i + 1)] = item[i].gw
          packInfo['nw' + (i + 1)] = item[i].nw
          packInfo['cube' + (i + 1)] = item[i].cube
        }
        currentPage += 1
        packInfo.currentPage = currentPage
        packInfo.allPages = allPages
        let paramsForPrint = {
          LabelName: form.caseDefMultiSkuSubLblName,
          PrinterName: form.caseDefPrinterNo,
          Parameters: packInfo,
          PrintNum: 1
        }
        printTasks.push($f.axios.post(nlpUrl, paramsForPrint))
      })
    }
    return Promise.all(printTasks)
      .catch((err) => {
        playErrorSound()
        $f.ui.showNotifyFailed('打印标签失败:' + $f.getAxiosErrMsg(err))
      })
      .finally(() => {
        $q.loading.hide()
      })
  } else {
    return Promise.resolve()
  }
}

const validPickLineId = function () {
  $d.pickLineId = $f.misc.tryExtractCompactStringWithIndex($d.pickLineId, 0)
  serverSuccessMessage.value = ''
  serverErrorMessage.value = ''
  isValidPickLine.value = false
  void v$.value
    .$validate()
    .then((valRes) => {
      if (valRes) {
        pickLineIdLoadingState.value = true
        let params = {
          pickLineId: $d.pickLineId
        }
        let focusOnWhenDone = ''
        $f.axios
          .get<PickLineInfoForCollect>('/wms/work/order/get-pick-line-info-for-collect', {params})
          .then((resp) => {
            $d.pickLineInfo = resp.data
            $d.collectContainer = resp.data.collectContainer
            if (resp.data.isAllowFillTheLabel) {
              serverErrorMessage.value = '该拣货明细已集货，无法再进行集货操作'
            }
          })
          .catch((err) => {
            playErrorSound()
            if (err.response?.status === 404) {
              serverErrorMessage.value = '该出拣货明细ID不存在'
            } else {
              serverErrorMessage.value = $f.getAxiosErrMsg(err)
            }
            resetPickLineInfo()
            focusOnWhenDone = 'pickLineId'
          })
          .finally(() => {
            pickLineIdLoadingState.value = false
            if (focusOnWhenDone !== '') {
              void nextTick(() => {
                pickLineId.value && pickLineId.value.focus()
              })
            }
          })
      }
    })
}
const pickLineId = ref<QInput | null>(null)
const resetPickLineInfo = function () {
  $d.pickLineInfo = {} as PickLineInfoForCollect
  v$.value.$reset()
}
let isPrintCollectLabel = window.localStorage.getItem('isPrintCollectLabel')
if (isPrintCollectLabel) $d.isPrintCollectLabel = JSON.parse(isPrintCollectLabel)
const fx = $f
const e$ = $f.getFieldErrStr
</script>

<style scoped>

</style>
